/**
 * chatStorage.js - 使用IndexedDB存储聊天记录的工具类
 */

// IndexedDB数据库配置
const DB_NAME = 'chatHistoryDB';
const DB_VERSION = 1;
const STORE_NAME = 'chatMessages';

/**
 * 初始化/打开IndexedDB数据库
 * @returns {Promise} 返回数据库实例的Promise
 */
export const initDB = () => {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(DB_NAME, DB_VERSION);
    
    // 数据库首次创建或升级时调用
    request.onupgradeneeded = (event) => {
      const db = event.target.result;
      
      // 如果没有消息存储，则创建
      if (!db.objectStoreNames.contains(STORE_NAME)) {
        // 创建以userId为索引的对象存储
        const store = db.createObjectStore(STORE_NAME, { keyPath: 'id', autoIncrement: true });
        store.createIndex('userId', 'userId', { unique: false });
        store.createIndex('timestamp', 'timestamp', { unique: false });
      }
    };
    
    // 成功打开数据库
    request.onsuccess = (event) => {
      console.log('IndexedDB初始化成功');
      resolve(event.target.result);
    };
    
    // 打开数据库失败
    request.onerror = (event) => {
      console.error('IndexedDB初始化失败:', event.target.error);
      reject(event.target.error);
    };
  });
};

/**
 * 保存消息到IndexedDB
 * @param {object} db - 数据库实例
 * @param {string} userId - 用户ID
 * @param {array} messages - 消息数组
 * @returns {Promise} 保存操作的Promise
 */
export const saveMessagesToIndexedDB = (db, userId, messages) => {
  if (!db) return Promise.reject('数据库未初始化');
  
  return new Promise((resolve, reject) => {
    // 每次保存整个消息记录
    const transaction = db.transaction([STORE_NAME], 'readwrite');
    const store = transaction.objectStore(STORE_NAME);
    
    // 清除该用户之前的所有记录
    const clearRequest = store.index('userId').openKeyCursor(IDBKeyRange.only(userId));
    
    clearRequest.onsuccess = (event) => {
      const cursor = event.target.result;
      if (cursor) {
        store.delete(cursor.primaryKey);
        cursor.continue();
      } else {
        // 添加新记录
        const addRequest = store.add({
          userId: userId,
          messages: JSON.parse(JSON.stringify(messages)), // 深拷贝消息
          timestamp: new Date().getTime()
        });
        
        addRequest.onsuccess = () => {
          console.log('聊天记录已保存');
          resolve();
        };
        
        addRequest.onerror = (event) => {
          console.error('保存聊天记录失败:', event.target.error);
          reject(event.target.error);
        };
      }
    };
    
    clearRequest.onerror = (event) => {
      console.error('清除旧聊天记录失败:', event.target.error);
      reject(event.target.error);
    };
    
    transaction.oncomplete = () => {
      console.log('事务完成');
    };
    
    transaction.onerror = (event) => {
      console.error('事务错误:', event.target.error);
      reject(event.target.error);
    };
  });
};

/**
 * 从IndexedDB加载消息
 * @param {object} db - 数据库实例
 * @param {string} userId - 用户ID
 * @returns {Promise} 包含消息数组的Promise
 */
export const loadMessagesFromIndexedDB = (db, userId) => {
  if (!db) return Promise.reject('数据库未初始化');
  
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readonly');
    const store = transaction.objectStore(STORE_NAME);
    const index = store.index('userId');
    
    // 获取指定用户的所有记录
    const request = index.openCursor(IDBKeyRange.only(userId));
    let latestRecord = null;
    let latestTimestamp = 0;
    
    request.onsuccess = (event) => {
      const cursor = event.target.result;
      if (cursor) {
        // 找到时间戳最新的记录
        if (cursor.value.timestamp > latestTimestamp) {
          latestTimestamp = cursor.value.timestamp;
          latestRecord = cursor.value;
        }
        cursor.continue();
      } else {
        // 游标完成，检查是否找到记录
        if (latestRecord) {
          console.log('已加载最新聊天记录');
          resolve(latestRecord.messages || []);
        } else {
          console.log('没有找到聊天记录');
          resolve([]);
        }
      }
    };
    
    request.onerror = (event) => {
      console.error('加载聊天记录失败:', event.target.error);
      reject(event.target.error);
    };
  });
};

/**
 * 清除所有聊天记录
 * @param {object} db - 数据库实例
 * @returns {Promise} 清除操作的Promise
 */
export const clearAllChatHistory = (db) => {
  if (!db) return Promise.reject('数据库未初始化');
  
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readwrite');
    const store = transaction.objectStore(STORE_NAME);
    const request = store.clear();
    
    request.onsuccess = () => {
      console.log('所有聊天记录已清除');
      resolve();
    };
    
    request.onerror = (event) => {
      console.error('清除聊天记录失败:', event.target.error);
      reject(event.target.error);
    };
  });
};

/**
 * 导出聊天记录为JSON文件
 * @param {array} messages - 消息数组
 * @param {string} userId - 用户ID
 * @returns {Promise} 导出操作的Promise
 */
export const exportChatHistory = (messages, userId) => {
  return new Promise((resolve, reject) => {
    try {
      if (!messages || messages.length === 0) {
        reject(new Error('没有聊天记录可导出'));
        return;
      }
      
      const chatData = {
        userId: userId,
        messages: messages,
        exportTime: new Date().toISOString()
      };
      
      const blob = new Blob([JSON.stringify(chatData, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `chat-history-${new Date().toISOString().slice(0, 10)}.json`;
      link.click();
      URL.revokeObjectURL(url);
      
      resolve();
    } catch (error) {
      console.error('导出聊天记录失败:', error);
      reject(error);
    }
  });
};

/**
 * 导入聊天记录
 * @param {File} file - 导入的JSON文件
 * @returns {Promise} 包含导入消息的Promise
 */
export const importChatHistory = (file) => {
  return new Promise((resolve, reject) => {
    if (!file) {
      reject(new Error('没有选择文件'));
      return;
    }
    
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target.result);
        
        // 验证导入的数据格式
        if (!data.messages || !Array.isArray(data.messages)) {
          throw new Error('无效的聊天记录格式');
        }
        
        resolve(data.messages);
      } catch (error) {
        console.error('导入聊天记录失败:', error);
        reject(error);
      }
    };
    
    reader.onerror = () => {
      reject(new Error('读取文件失败'));
    };
    
    reader.readAsText(file);
  });
}; 